package com.example.app.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;

public class DeepSeekClient {
    private static final String TAG = "DeepSeekClient";
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    private final String apiKey;

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private final OkHttpClient client = new OkHttpClient();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    public DeepSeekClient(String apiKey) {
        this.apiKey = apiKey;
    }

    public interface ResponseCallback {
        void onStart();
        void onStream(String partialResponse, boolean isLastChunk);
        void onComplete(String fullResponse);
        void onError(String error);
    }

    public void sendMessage(String message, ResponseCallback callback) {
        try {
            // 通知开始
            mainHandler.post(callback::onStart);

            // 构建请求数据
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("model", "deepseek-chat");
            jsonBody.put("stream", true); // 启用流式输出

            // 添加流式选项
            JSONObject streamOptions = new JSONObject();
            streamOptions.put("include_usage", true);
            jsonBody.put("stream_options", streamOptions);

            JSONArray messagesArray = new JSONArray();
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", message);
            messagesArray.put(userMessage);

            jsonBody.put("messages", messagesArray);

            Log.d(TAG, "发送请求: " + jsonBody.toString());

            RequestBody body = RequestBody.create(jsonBody.toString(), JSON);
            Request request = new Request.Builder()
                    .url(API_URL)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .addHeader("Content-Type", "application/json")
                    .post(body)
                    .build();

            // 发送请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    String errorMsg = "请求失败: " + e.getMessage();
                    Log.e(TAG, errorMsg, e);
                    mainHandler.post(() -> callback.onError(errorMsg));
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        String errorMsg = "API返回错误: " + response.code();
                        Log.e(TAG, errorMsg);
                        mainHandler.post(() -> callback.onError(errorMsg));
                        return;
                    }

                    try {
                        ResponseBody responseBody = response.body();
                        if (responseBody == null) {
                            throw new IOException("响应体为空");
                        }

                        BufferedSource source = responseBody.source();
                        StringBuilder fullResponse = new StringBuilder();

                        while (!source.exhausted()) {
                            String line = source.readUtf8Line();
                            if (line == null) {
                                break;
                            }

                            Log.d(TAG, "流式原始返回: " + line);

                            // 处理流式返回的SSE格式数据
                            if (line.startsWith("data:")) {
                                String data = line.substring(5).trim();

                                // 处理完成标志
                                if ("[DONE]".equals(data)) {
                                    String finalText = fullResponse.toString();
                                    mainHandler.post(() -> callback.onComplete(finalText));
                                    break;
                                }

                                try {
                                    JSONObject jsonData = new JSONObject(data);
                                    if (jsonData.has("choices")) {
                                        JSONArray choicesArray = jsonData.getJSONArray("choices");
                                        if (choicesArray.length() > 0) {
                                            JSONObject firstChoice = choicesArray.getJSONObject(0);
                                            JSONObject delta = firstChoice.getJSONObject("delta");

                                            if (delta.has("content")) {
                                                String content = delta.getString("content");
                                                fullResponse.append(content);

                                                // 逐字发送部分回复，并每次都强制滚动
                                                final String currentText = content;
                                                final boolean isLastChunk = firstChoice.has("finish_reason") && !firstChoice.isNull("finish_reason");
                                                mainHandler.post(() -> {
                                                    callback.onStream(currentText, isLastChunk);
                                                });
                                            }
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e(TAG, "解析流式返回出错", e);
                                }
                            }
                        }

                        // 确保完成回调被触发
                        if (fullResponse.length() > 0) {
                            final String finalText = fullResponse.toString();
                            mainHandler.post(() -> callback.onComplete(finalText));
                        } else {
                            mainHandler.post(() -> callback.onError("未收到有效回复"));
                        }

                    } catch (Exception e) {
                        Log.e(TAG, "处理响应失败", e);
                        mainHandler.post(() -> callback.onError("处理响应失败: " + e.getMessage()));
                    }
                }
            });

        } catch (Exception e) {
            Log.e(TAG, "创建请求失败", e);
            mainHandler.post(() -> callback.onError("创建请求失败: " + e.getMessage()));
        }
    }
} 